// pages/cart/index.js
import { login, showToast } from "../../utils/asyncWx"
import {request} from "../../request/request.js"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        address:{},
        totalPrice:0,
        totalNum:0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let totalPrice = 0;
        let totalNum = 0;
        /* 一返回都会刷新地址 */
        const address = wx.getStorageSync("address");
        if(address.userName){
            address.all = address.provinceName+address.cityName+address.countyName+address.detailInfo
        }
        /* 获取缓存中的购物车数据 */
        const cart = wx.getStorageSync("cart") || [];
        //过滤购物车 只有选中的才能支付
        const checkedCart = cart.filter(v=>v.checked)
        checkedCart.forEach(v=>{
            totalNum+=v.num;
            totalPrice+=v.num*v.goods_price
        })
        this.setData({
            address,checkedCart,totalNum,totalPrice
        })
    },


    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

/* 点击支付 */
async handleGetUserInfo(e){
    /* 判断缓存是否有token */
    const token = wx.getStorageSync("token");
    if(!token){
        console.log(e);
        /* 获取用户参数 */
        const {encryptedData,rawData,iv,signature} = e.detail
        /* 获取code */
        const {code} = await login();
        /* 封装请求数据 一起传进去 */
        const loginParams = {encryptedData,rawData,iv,signature,code};
        /* 发送请求 获取token */
        let {token} = await request({url:"/users/wxlogin",data:loginParams,method:"post"})
        /* 没获取到token捏。。可能时接口问题 评论区的接口也用不了 */
        if(!token){
            wx.setStorageSync("token" , "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo")
        }
    }
    /* 创建订单 */
    /* 请求头参数 */
    // const header = {Authorization:token}
    /* 请求体参数 */ 
    const order_price = this.data.totalPrice
    const consignee_addr = this.data.address.all
    const cart = this.data.checkedCart
    let goods = [];
    cart.forEach(v=>goods.push({
        goods_id:v.goods_id,
        goods_number:v.num,
        goods_price:v.goods_price
    }))
    /* 发送请求 */
    /* 封装请求参数 */
    const orderParams = {order_price,consignee_addr,goods}
    const res = await request({url:"/my/orders/create" , method:"POST", data:orderParams })
    showToast({title:"因为token失效 这里假装已经支付成功"})
    let newCart = wx.getStorageSync("cart");
    newCart=newCart.filter(v=>!v.checked)
    wx.setStorageSync("cart", newCart);
    wx.navigateTo({
        url: '/pages/order/index'
    });
},




    /* 结算 */

})